<template>
  <div>
    <div class="flexrowbetween flexwrapper" style="align-items: flex-start">
      <div class="iconbox flexcenter commhover" @click="resetQuery">
        <i class="el-icon-refresh f-20" :class="{ rotate: isrefresh }"></i>
      </div>
      <div>
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          label-width="0"
        >
          <el-form-item prop="keyword">
            <el-input
              class="searchinput"
              v-model="queryParams.keyword"
              placeholder="请输入活动名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item class="mr_0">
            <el-dropdown trigger="click">
              <el-button size="mini" class="nor_border plr_9">
                <svg-icon class-name="f-14" icon-class="listicon" />
                <i class="el-icon-caret-bottom el-icon--right"></i>
                <!-- <i class="el-icon-s-fold f-14"></i> -->
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <div class="dropbody">
                  <el-checkbox-group
                    v-model="checkedOption"
                    class="flexcolumn"
                    @change="changeSelect"
                  >
                    <el-checkbox
                      v-for="(item, index) in selectoptions"
                      :label="item.label"
                      :key="index"
                      class="m_5"
                      >{{ item.label }}</el-checkbox
                    >
                  </el-checkbox-group>
                </div>
              </el-dropdown-menu>
            </el-dropdown>
          </el-form-item>
          <el-form-item>
            <el-button
              size="mini"
              class="nol_border"
              :loading="exportloading"
              @click="download"
            >
              <svg-icon class-name="f-14" icon-class="export" />
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              class="f-14"
              type=""
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
            ></el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-table ref="tablelayout" v-loading="loading" :data="tableData" border class="commtable"  >
      <el-table-column
        label=""
        prop="search_engine"
        width="80px"
        align="center"
      >
        <template slot-scope="scope">
          <div style="height:46px">
            <el-popover :key="scope.row.id"
                placement="bottom-start"
                width="120"
                trigger="hover">
                <qrcode-img
                  :url="scope.row.linkurl"
                  :id="'qrcode' + scope.row.id"
                  :width="126"
                />
                <qrcode-img slot="reference"
                  :url="scope.row.linkurl"
                  :id="'qrcode2' + scope.row.id"
                  :width="46"
                />
              </el-popover>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="平台"
        prop="platName"
        width="120px"
        align="center"
        v-if="activeOption.includes('平台')"
      >
        <template slot-scope="scope">
          {{ scope.row.task ? scope.row.task.tp_name : "-" }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="activeOption.includes('活动id')"
        label="活动id"
        prop="tp_id"
        width="100px"
        align="center"
      />
      <el-table-column
        v-if="activeOption.includes('活动分类')"
        label="活动分类"
        width="120px"
        align="center"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.template"
            >{{
              scope.row.template.template_class
                ? scope.row.template.template_class.name
                : "-"
            }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="activeOption.includes('活动名称')"
        label="活动名称"
        prop="name"
        min-width="260px"
        align="center"
      />
      <el-table-column
        v-if="activeOption.includes('活动编号')"
        label="活动编号"
        prop="id"
        width="100px"
        align="center"
      />
      <el-table-column
        v-if="activeOption.includes('活动时间')"
        label="活动时间"
        prop="time"
        width="300px"
        align="center"
      >
        <template slot-scope="scope">
          <span
            >{{ scope.row.draw_startime }} - {{ scope.row.draw_endtime }}</span
          >
        </template>
      </el-table-column>
      <el-table-column
        v-if="activeOption.includes('全部状态')"
        label="全部状态"
        align="center"
        width="100px"
      >
        <template slot-scope="scope">
          <template v-if="scope.row.status == 1">
            <el-tag
              v-if="new Date(scope.row.draw_startime).getTime() > Date.now()"
              type="warning"
              class="tag_success"
              >未开始</el-tag
            >
            <el-tag v-else type="success" class="tag_success">进行中</el-tag>
          </template>
          <el-tag v-if="scope.row.status == 4" type="danger" class="tag_warning"
            >已结束</el-tag
          >
          <el-tag v-if="scope.row.status == 0" type="info" class="tag_info"
            >未发布</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        v-if="activeOption.includes('开奖人数')"
        label="开奖人数"
        width="150px"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.draw_win_num }}/{{ scope.row.draw_num }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="activeOption.includes('奖品/商品详情')"
        label="奖品/商品详情"
        min-width="180px"
        align="center"
      >
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" placement="top-start">
            <div slot="content">
              <!-- 奖品一<br/>第二行信息 -->
              <span v-for="(item,index) in scope.row.drawlist" :key="index">{{item.level_name}} {{item.draw_name}}：{{item.total}}份<br/></span>
            </div>
            <span class="c_primary commhover">查看详情</span>
          </el-tooltip>
          <!-- <span class="c_primary commhover" @click="showDetail(scope.row.introduce)">查看详情</span> -->
          <!-- <span class="wordlimit">{{ scope.row.introduce }}</span> -->
        </template>
      </el-table-column>
      <el-table-column
        v-if="activeOption.includes('开奖状态')"
        label="开奖状态"
        width="150px"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.type_name || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="activeOption.includes('智能防刷')"
        label="智能防刷"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{
            scope.row.task_config.safe_name
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="activeOption.includes('创建时间')"
        label="创建时间"
        align="center"
        width="160px"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.create_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="activeOption.includes('创建人')"
        label="创建人"
        align="center"
        width="130px"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.member.user_login }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="created_at"
        label="操作"
        width="320px"
        fixed="right"
        align="center"
      >
        <template slot-scope="scope">
          <div class="flex btnflex justifycenter flexwrapper">
            <div
              v-if="scope.row.status == 0"
              class="commhover btn_green mr_10 c_fff"
              @click="handleFabu(scope.row)"
            >
              <!-- <svg-icon icon-class="fabu"  class-name="f-14" />  -->
              发布
            </div>
            <div
              class="commhover btn_yellow mr_10 c_fff"
              @click="handleEdit(scope.row)"
            >
              <!-- <i class="el-icon-edit-outline f-14"></i> -->
              编辑
            </div>
            <div
              class="commhover btn_blue mr_10 c_fff"
              @click="handleDetail(scope.row)"
            >
              <!-- <svg-icon icon-class="yulan"  class-name="f-14" /> -->
              预览
            </div>
            <div
              class="commhover btn_green mr_10 c_fff"
              @click="handleDetele(scope.row)"
            >
              <!-- <i class="el-icon-delete f-14"></i>  -->
              删除
            </div>
            <div v-if="scope.row.type == 1" class="commhover btn_blue mr_10 c_fff"
              @click="handleOpenDraw(scope.row)"
            >
              指定开奖
            </div>
            <div v-if="scope.row.type == 2||scope.row.type == 3"
              class="commhover btn_blue mr_10 c_fff"
              @click="handleOpenTime(scope.row)"
            >
              <!-- <svg-icon icon-class="date"  class-name="f-14" /> -->
              定时开奖
            </div>
            <!-- <div class="commhover btn_blue mr_10 c_fff" @click="handleLog(scope.row)" >
                <svg-icon icon-class="rizhi"  class-name="f-14" />日志 
              </div> -->
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.num"
      @pagination="getList"
    />

    <el-dialog
      title="确认发布"
      :visible.sync="dialogVisible"
      width="680px"
      class="dialogheaderbg"
      :before-close="handleClose"
      :close-on-click-modal='false'
    >
      <fabu-comp v-if="dialogVisible" :row="row" @close="handleClose" />
    </el-dialog>

    <!-- 日志 -->
    <el-dialog
      class="dialogheaderbg"
      title="访问日志"
      :visible.sync="dialoglogVisible"
      width="80%"
      :close-on-click-modal='false'
      :before-close="handleLogClose"
    >
      <log-table :rowId="rowId" @close="handleLogClose" />
    </el-dialog>

    <!-- 预览 -->
    <el-dialog
      title=""
      :visible.sync="dialogView"
      width="1000px"
      :show-close="false"
      class="noheaderdia"
      :close-on-click-modal='false'
      :before-close="handleViewClose"
    >
      <view-comp
        v-if="dialogView"
        :row="row"
        @close="handleViewClose"
        @edit="handleEdit"
      />
    </el-dialog>

    <el-dialog
      class="dialogheaderbg"
      title="定时开奖"
      :visible.sync="timeopen"
      width="80%"
      :before-close="handleCloseTime"
      :close-on-click-modal='false'
    >
      <time-comp v-if="timeopen" :row="row" @close="handleCloseTime" />
    </el-dialog>

    <el-dialog
      class="dialogheaderbg"
      title="指定开奖"
      :visible.sync="drawopen"
      width="80%"
      :before-close="handleCloseDraw"
      :close-on-click-modal='false'
    >
      <draw-comp v-if="drawopen" :row="row" @close="handleCloseDraw" />
    </el-dialog>

    <el-dialog
      class="dialogheaderbg"
      title="查看详情"
      :visible.sync="detailopen"
      width="680px"
      :before-close="handleCloseDetail"
      :close-on-click-modal='false'
    >
      <div>
        <Tinymce  ref="tinymce" :msg="detail"></Tinymce>
      </div>
      <!-- <detail-comp v-if="detailopen" :detail='detail' @close="handleCloseDetail" /> -->
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import {
  taskIndex,
  taskWaitingIndex,
  taskPublishIndex,
  taskWorkingIndex,
  btnDelete,
  taskEndingIndex,
  taskIndexExport,
  taskWaitingIndexExport,
  taskPublishIndexExport,
  taskWorkingIndexExport,
  taskEndingIndexExport,
} from "@/api/active";
import FabuComp from "./components/FabuComp.vue";
import LogTable from "./components/LogTable.vue";
import ViewComp from "./components/ViewComp.vue";
import { getMemberToken } from "@/api/member";
import TimeComp from "./components/TimeComp.vue";
import DrawComp from "./components/DrawComp.vue";
import DetailComp from './components/DetailComp.vue';
import QrcodeImg from '@/components/QrcodeImg';
import Tinymce from "@/components/Tinymce";

export default {
  data() {
    return {
      queryParams: {
        page: 1,
        num: 10,
        keyword: undefined,
      },
      total: 1,
      loading: false,
      tableData: [],
      checkedOption: [],
      isrefresh: false,
      selectoptions: [
        { id: 1, label: "平台" },
        { id: 2, label: "活动id" },
        { id: 3, label: "活动分类" },
        { id: 4, label: "活动名称" },
        { id: 5, label: "活动编号" },
        { id: 6, label: "活动时间" },
        { id: 7, label: "全部状态" },
        { id: 8, label: "开奖人数" },
        { id: 9, label: "奖品/商品详情" },
        { id: 13, label: '开奖状态' },
        { id: 10, label: "智能防刷" },
        { id: 11, label: "创建时间" },
        { id: 12, label: "创建人" },
      ],
      dialogVisible: false,

      // 日志
      dialoglogVisible: false,
      rowId: "",

      // 预览
      dialogView: false,
      timeopen: false,
      row: "",
      exportloading: false,

      detailopen:false,
      detail:null,
      detailloading:false,

      drawopen:false
    };
  },

  props: {
    type: {
      type: Number,
      default: 1,
    },
  },

  components: {
    FabuComp,
    LogTable,
    ViewComp,
    TimeComp,
    DetailComp,
    QrcodeImg,
    Tinymce,
    DrawComp
  },

  computed: {
    ...mapState({
      activeOption: (state) => state.paramsoption.activeOption,
    }),
  },

  created() {
    let activeOption = JSON.parse(localStorage.getItem("activeOption"));
    if (activeOption) {
      this.changeSelect(activeOption);
    }
    this.checkedOption = this.activeOption;
    this.getList();
  },
  
  activated() {
    this.$nextTick(() => {
      //在数据加载完，重新渲染表格
      this.$refs.tablelayout && this.$refs.tablelayout.doLayout()
    });
  },

  // updated() {
  //   this.$nextTick(() => {
  //     //在数据加载完，重新渲染表格
  //     this.$refs.tablelayout && this.$refs.tablelayout.doLayout();
  //   });
  // },

  methods: {
    getList() {
      this.loading = true;
      let params = {
        page: this.queryParams.page,
        num: this.queryParams.num,
      };
      if (this.queryParams.keyword) {
        params.keyword = this.queryParams.keyword;
      }
      if (this.type == 99) {
        //全部
        taskIndex(params).then((response) => {
          this.tableData = response.data.list.map((item) => {
            let params = {
              ...item,
              linkurl: this.h5domain + "?id=" + item.id,
              drawlist: item.task_draw.map(draw=>({...draw,total: Number(draw.num)+Number(draw.old_num)}))
            }
            if(item.task_comfort){
              params.drawlist.push({...item.task_comfort,total: Number(item.task_comfort.num)+Number(item.task_comfort.old_num)})
            }
            return params
          });
          console.log('this.tableData:',this.tableData)
          this.total = response.data.count;
          this.loading = false;
          this.isrefresh = false;
          // this.$nextTick(() => {
          //   //在数据加载完，重新渲染表格
          //   this.$refs.tablelayout && this.$refs.tablelayout.doLayout();
          // });
          
        });
      } else if (this.type == 9) {
        //未发布
        taskWaitingIndex(params).then((response) => {
          // this.tableData = response.data.list;
          this.tableData = response.data.list.map((item) => {
            let params = {
              ...item,
              linkurl: this.h5domain + "?id=" + item.id,
              drawlist: item.task_draw.map(draw=>({...draw,total: Number(draw.num)+Number(draw.old_num)}))
            }
            if(item.task_comfort){
              params.drawlist.push({...item.task_comfort,total: Number(item.task_comfort.num)+Number(item.task_comfort.old_num)})
            }
            return params
          });
          this.total = response.data.count;
          this.loading = false;
          this.isrefresh = false;
          // this.$nextTick(() => {
          //   //在数据加载完，重新渲染表格
          //   this.$refs.tablelayout && this.$refs.tablelayout.doLayout();
          // });
        });
      } else if (this.type == "0") {
        //未开始
        taskPublishIndex(params).then((response) => {
          // this.tableData = response.data.list;
          this.tableData = response.data.list.map((item) => {
            let params = {
              ...item,
              linkurl: this.h5domain + "?id=" + item.id,
              drawlist: item.task_draw.map(draw=>({...draw,total: Number(draw.num)+Number(draw.old_num)}))
            }
            if(item.task_comfort){
              params.drawlist.push({...item.task_comfort,total: Number(item.task_comfort.num)+Number(item.task_comfort.old_num)})
            }
            return params
          });
          this.total = response.data.count;
          this.loading = false;
          this.isrefresh = false;
          // this.$nextTick(() => {
          //   //在数据加载完，重新渲染表格
          //   this.$refs.tablelayout && this.$refs.tablelayout.doLayout();
          // });
        });
      } else if (this.type == 1) {
        //进行中
        taskWorkingIndex(params).then((response) => {
          // this.tableData = response.data.list;
          this.tableData = response.data.list.map((item) => {
            let params = {
              ...item,
              linkurl: this.h5domain + "?id=" + item.id,
              drawlist: item.task_draw.map(draw=>({...draw,total: Number(draw.num)+Number(draw.old_num)}))
            }
            if(item.task_comfort){
              params.drawlist.push({...item.task_comfort,total: Number(item.task_comfort.num)+Number(item.task_comfort.old_num)})
            }
            return params
          });
          this.total = response.data.count;
          this.loading = false;
          this.isrefresh = false;
          // this.$nextTick(() => {
          //   //在数据加载完，重新渲染表格
          //   this.$refs.tablelayout && this.$refs.tablelayout.doLayout();
          // });
        });
      } else if (this.type == 4) {
        //已结束
        taskEndingIndex(params).then((response) => {
          // this.tableData = response.data.list;
          this.tableData = response.data.list.map((item) => {
            let params = {
              ...item,
              linkurl: this.h5domain + "?id=" + item.id,
              drawlist: item.task_draw.map(draw=>({...draw,total: Number(draw.num)+Number(draw.old_num)}))
            }
            if(item.task_comfort){
              params.drawlist.push({...item.task_comfort,total: Number(item.task_comfort.num)+Number(item.task_comfort.old_num)})
            }
            return params
          });
          this.total = response.data.count;
          this.loading = false;
          this.isrefresh = false;
          // this.$nextTick(() => {
          //   //在数据加载完，重新渲染表格
          //   this.$refs.tablelayout && this.$refs.tablelayout.doLayout();
          // });
        });
      }
    },

    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },

    resetQuery() {
      this.isrefresh = true;
      this.resetForm("queryForm");
      this.handleQuery();
    },

    changeSelect(arr) {
      this.$store.commit("SET_ACTIVEOPTION", arr);
      this.$nextTick(() => {
        //在数据加载完，重新渲染表格
        this.$refs.tablelayout && this.$refs.tablelayout.doLayout();
      });
    },

    handleCommand(command) {
      console.log(command);
    },

    showDetail(detail){
      // showDetail
      this.detailloading = true
      this.detail = detail
      this.detailopen = true
      setTimeout(()=>{
        this.detailloading = false
      },2000)
    },

    handleCloseDetail(){
      this.detail = null
      this.detailopen = false
    },

    handleFabu(row) {
      this.row = row;
      this.dialogVisible = true;
    },

    handleClose(type) {
      if (type == 1) {
        this.getList();
      }
      this.dialogVisible = false;
    },

    handleLog(row) {
      this.rowId = row.id;
      this.dialoglogVisible = true;
    },

    handleLogClose() {
      this.dialoglogVisible = false;
    },

    // 预览
    handleDetail(row) {
      this.row = row;
      this.dialogView = true;
    },

    handleViewClose(type) {
      if (type == 1) {
        this.getList();
      }
      this.dialogView = false;
    },

    handleEdit(row) {
      getMemberToken({ user_id: row.member.id }).then((res) => {
        console.log(res.data);
        let token = res.data;
        window.open(
          this.userdomain + "login?token=" + token + "&activeId=" + row.id
        );
      });
    },

    handleOpenTime(row) {
      this.row = row;
      this.timeopen = true;
    },

    handleCloseTime() {
      this.timeopen = false;
    },

    handleOpenDraw(row){
      this.row = row
      this.drawopen = true
    },

    handleCloseDraw() {
      this.drawopen = false;
    },

    // 删除
    handleDetele(row) {
      this.$confirm("确定删除该条的数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          btnDelete({
            id: row.id,
          }).then(() => {
            this.$modal.msgSuccess("删除成功");
            this.getList();
          });
        })
        .catch(() => {});
    },

    download() {
      let params = {
        head: [
          "平台",
          "活动ID",
          "活动分类",
          "活动名称",
          "活动编号",
          "活动时间(开始时间)",
          "活动时间(结束时间)",
          "全部状态",
          "开奖人数",
          "开奖状态",
          "智能防刷",
          "创建时间",
          "创建人",
          "参与人数",
        ],
        keys: [
          "tp_task_name",
          "tp_id",
          "template.template_class.name",
          "name",
          "id",
          "draw_startime",
          "draw_endtime",
          "status_name",
          "draw_win_num",
          "type_name",
          "task_config.safe_name",
          "create_time",
          "member.user_login",
          "draw_num",
        ],
      };
      if (this.queryParams.keyword) {
        params.keyword = this.queryParams.keyword;
      }
      this.exportloading = true;
      if (this.type == 99) {
        //全部
        taskIndexExport(params).then((res) => {
          let url = res.data;
          this.$message.success("正在下载，请稍后");
          var a = document.createElement("a");
          a.setAttribute("href", url);
          a.click();
          this.exportloading = false;
        })
        
      } else if (this.type == 9) {
        //未发布
        taskWaitingIndexExport(params).then((res) => {
          let url = res.data;
          this.$message.success("正在下载，请稍后");
          var a = document.createElement("a");
          a.setAttribute("href", url);
          a.click();
          this.exportloading = false;
        });
      } else if (this.type == "0") {
        //未未开始
        taskPublishIndexExport(params).then((res) => {
          let url = res.data;
          this.$message.success("正在下载，请稍后");
          var a = document.createElement("a");
          a.setAttribute("href", url);
          a.click();
          this.exportloading = false;
        });
      } else if (this.type == 1) {
        //进行中
        taskWorkingIndexExport(params).then((res) => {
          let url = res.data;
          this.$message.success("正在下载，请稍后");
          var a = document.createElement("a");
          a.setAttribute("href", url);
          a.click();
          this.exportloading = false;
        });
      } else if (this.type == 4) {
        //已结束
        taskEndingIndexExport(params).then((res) => {
          let url = res.data;
          this.$message.success("正在下载，请稍后");
          var a = document.createElement("a");
          a.setAttribute("href", url);
          a.click();
          this.exportloading = false;
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.iconbox {
  width: 32px;
  height: 32px;
  border: 1px solid #eee;
  border-radius: 2px;
}
.imgmini {
  width: 40px;
  height: 40px;
  margin: auto;
}
.imgbox {
  width: 120px;
  height: 120px;
}

</style>
<style lang="scss">
.noheaderdia {
  .el-dialog__header {
    padding: 0 !important;
  }
  .el-dialog__body {
    padding: 0 !important;
  }
}

</style>